package com.yeqian.system.handle;

import com.yeqian.entity.ResultJson;
import com.yeqian.system.exceptions.SystemAccountException;
import lombok.extern.slf4j.Slf4j;
import netscape.security.ForbiddenTargetException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalControllerExceptionHandler {

    /**
     * 前端参数错误   400
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = {MethodArgumentTypeMismatchException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultJson methodArgumentTypeMismatchException(MethodArgumentTypeMismatchException exception) {
        log.error(exception.getMessage(),exception);
        return  ResultJson.error(400,"客户端错误，请检查当前环境或联系管理员");
    }


    /**
     * 请求权限不够  403
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = {ForbiddenTargetException.class})
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ResultJson noHandlerFoundException(ForbiddenTargetException exception) {
        log.error(exception.getMessage(),exception);
        return  ResultJson.error(403,HttpStatus.FORBIDDEN.getReasonPhrase());
    }


    /**
     * 请求路径错误   404
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = {NoHandlerFoundException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResultJson noHandlerFoundException(NoHandlerFoundException exception) {
        log.error(exception.getMessage(),exception);
        return  ResultJson.error(404,"您所访问的网页不存在，请检查");
    }

    /**
     * 运行时异常    500
     *
     * @param re
     * @return
     */
//    @ExceptionHandler(value = {RuntimeException.class})
//    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
//    public ResultJson runtimeException(RuntimeException re) {
//        log.error(re.getMessage(),re);
//        return  ResultJson.error(500,"服务器错误，请联系管理员解决");
//    }

    /**
     * 系统帐户异常
     * @param re
     * @return
     */
    @ExceptionHandler(value = {SystemAccountException.class})
    public ResultJson systemAccountException(SystemAccountException re) {
        log.error(re.getMessage(),re);
        return  ResultJson.error(200,re.getMessage());
    }
}
